<?php

namespace App\Library\Rules;

use Exception;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Log;
class IdNumRule implements Rule
{
    private string $errorMessage = '身份证号码格式错误';

    /**
     * passes
     * @param string $attribute
     * @param mixed $value
     * @return boolean
     */
    public function passes($attribute, $value): bool
    {
        if (!preg_match(__('com.idNumReg'), $value)) return false;
        $str = substr($value, 6, 8);
        $date = implode('-', [substr($str, 0, 4), substr($str, 4, 2), substr($str, 6)]);
        try {
            $dateTime = now()->parse($date);
        } catch (Exception $e) {
            Log::info($e->getMessage());
            return false;
        }
        if ($dateTime->format('Y-m-d') === $date) return true;
        else return false;
    }

    /**
     * message
     * @return string
     */
    public function message(): string
    {
        return $this->errorMessage;
    }
}
